﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
using System.Data;

namespace GtsServer.Common
{
    public class LogWrite
    {
        /// <summary>
        /// 写入消息
        /// </summary>
        /// <param name="msg"></param>
        public static void WriteLog(string msg)
        {
            Thread r = new Thread(new ParameterizedThreadStart(ThreadWriteLog));
            r.Start(msg);
        }

        public static void ThreadWriteLog(object state)
        {
            string msg = (string)state;
            if (msg != string.Empty)
            {
                LogWriteModel model = new LogWriteModel();
                model.Title = string.Empty;
                model.Exception = msg;
                model.Type = (int)LogTypeEnum.info;
                model.LogTime = DateTime.Now;

                bool b = AddLog(model);
            }
        }

        /// <summary>
        /// 写入错误信息
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteLog(Exception ex, string title)
        {
            Tuple<Exception, string> myTuple = new Tuple<Exception, string>(ex, title);
            Thread t = new Thread(new ParameterizedThreadStart(ThreadWriteErrorLog));
            t.Start(myTuple);
        }

        public static void ThreadWriteErrorLog(object state)
        {
            Exception ex = null;
            string title = string.Empty;
            Tuple<Exception, string> myTuple = (Tuple<Exception, string>)state;
            ex = myTuple.Item1;
            title = myTuple.Item2;
            if (ex != null)
            {
                LogWriteModel model = new LogWriteModel();
                model.Title = title + ex.Message;
                //model.Message = ex.Message;
                model.Exception = ex.StackTrace;
                model.Type = (int)LogTypeEnum.error;
                model.LogTime = DateTime.Now;

                bool b = AddLog(model);
            }
        }

        /// <summary>
        /// 写入消息
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteLog(string msg, string title)
        {
            Tuple<string, string> myTuple = new Tuple<string, string>(msg, title);
            Thread t = new Thread(new ParameterizedThreadStart(ThreadWriteMsgLog));
            t.Start(myTuple);
        }

        private static void ThreadWriteMsgLog(object state)
        {
            string msg = string.Empty;
            string title = string.Empty;
            Tuple<string, string> myTuple = (Tuple<string, string>)state;
            msg = myTuple.Item1;
            title = myTuple.Item2;
            if (msg != string.Empty)
            {
                LogWriteModel model = new LogWriteModel();
                model.Title = title;
                // model.Message = ex.Message;
                model.Exception = msg;
                model.Type = (int)LogTypeEnum.info;
                model.LogTime = DateTime.Now;

                bool b = AddLog(model);
            }
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        public static bool AddLog(LogWriteModel model)
        {
            bool b = false;
            string sql = @"INSERT INTO dbo.LogCenter (title,[message],[exception],[type],logtime,remark) 
                           VALUES (@Title,@Message,@Exception,@Type,@LogTime,@Remark)";



            SqlConnection sqlcon = new SqlConnection(Configuration.GetConnectionStr());
            try
            {
                SqlCommand sqlcmd = new SqlCommand(sql, sqlcon);
                sqlcmd.Parameters.Add(new SqlParameter("@Title", model.Title ?? ""));
                sqlcmd.Parameters.Add(new SqlParameter("@Message", model.Message ?? ""));
                sqlcmd.Parameters.Add(new SqlParameter("@Exception", model.Exception ?? ""));
                sqlcmd.Parameters.Add(new SqlParameter("@Type", model.Type != null ? model.Type : 0));
                sqlcmd.Parameters.Add(new SqlParameter("@LogTime", model.LogTime != null ? model.LogTime : DateTime.Now));
                sqlcmd.Parameters.Add(new SqlParameter("@Remark", model.Remark ?? ""));
                sqlcon.Open();
                b = sqlcmd.ExecuteNonQuery() > 0 ? true : false;
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                sqlcon.Close();
                //throw ex;
                //WriteLog(ex, "LogWrite.AddLog");

            }
            return b;
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public static int GetCount(LogWriteModel model)
        {
            int count = 0;
            string timeStr = model.LogTime.ToString("dd/MM/yyyy");
            //拼接sql语句
            string sql = "select count(*) from logcenter where";
            if (model.Type != 0) sql += " type=" + model.Type + " and";
            if (!string.IsNullOrWhiteSpace(timeStr)) sql += " convert(varchar,logtime,103)='" + timeStr + "' and";
            if (!string.IsNullOrWhiteSpace(model.Title)) sql += " title like '%" + model.Title.Trim() + "%' and";
            if (!string.IsNullOrWhiteSpace(model.Exception)) sql += " exception like '%" + model.Exception.Trim() + "%' ";
            if (sql.EndsWith("where")) sql = sql.Substring(0, sql.LastIndexOf("where"));
            if (sql.EndsWith("and")) sql = sql.Substring(0, sql.LastIndexOf("and"));
            SqlConnection sqlcon = new SqlConnection(Configuration.GetConnectionStr());
            try
            {
                sqlcon.Open();
                SqlCommand cmd = new SqlCommand(sql, sqlcon);
                count = Convert.ToInt32(cmd.ExecuteScalar());
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                if (sqlcon.State == ConnectionState.Open) sqlcon.Close();
                WriteLog(ex, "LogWrite.GetCount");
            }
            return count;
        }

        /// <summary>
        /// 分页获取日志m
        /// </summary>
        public static List<LogWriteModel> GetLogListsByPaging(LogWriteModel model, int pageSize, int pageIndex)
        {
            List<LogWriteModel> lists = new List<LogWriteModel>();
            int skipCount = pageSize * (pageIndex - 1);
            string timeStr = model.LogTime.ToString("dd/MM/yyyy");
            string andString = "";
            //拼接sql语句
            string sql = "select top " + pageSize + " * from logcenter where id not in(select top " + skipCount + " id from logcenter where";
            if (model.Type != 0) andString += " type=" + model.Type + " and";
            if (!string.IsNullOrWhiteSpace(timeStr)) andString += " convert(varchar,logtime,103)='" + timeStr + "' and";
            if (!string.IsNullOrWhiteSpace(model.Title)) andString += " title like '%" + model.Title.Trim() + "%' and";
            if (!string.IsNullOrWhiteSpace(model.Exception)) andString += " exception like '%" + model.Exception.Trim() + "%' ";
            if (andString.EndsWith("and")) andString = andString.Substring(0, andString.LastIndexOf("and"));
            sql += andString + " order by id desc) and" + andString + " order by id desc";
            SqlConnection sqlcon = new SqlConnection(Configuration.GetConnectionStr());
            try
            {
                SqlCommand cmd = new SqlCommand(sql, sqlcon);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    LogWriteModel newModel = new LogWriteModel();
                    newModel.Title = row["title"] == null ? "" : row["title"].ToString();
                    newModel.Message = row["message"] == null ? "" : row["message"].ToString();
                    newModel.Exception = row["exception"] == null ? "" : row["exception"].ToString();
                    newModel.Type = row["type"] == null ? 0 : row["type"].Ext_ToInt();
                    newModel.LogTime = row["logTime"] == null ? DateTime.Now : row["logTime"].Ext_ToDateTime();
                    newModel.Remark = row["remark"] == null ? "" : row["remark"].ToString();
                    lists.Add(newModel);
                }
                sqlcon.Close();
            }
            catch (Exception ex)
            {
                if (sqlcon.State == ConnectionState.Open) sqlcon.Close();
                WriteLog(ex, "LogWrite.GetLogListsByPaging");
            }
            return lists;
        }
    }

    public class LogWriteModel
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }
        public int Type { get; set; }
        public DateTime LogTime { get; set; }
        public string Remark { get; set; }
    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogTypeEnum
    {
        /// <summary>
        /// 消息
        /// </summary>
        info = 1,

        /// <summary>
        /// 错误
        /// </summary>
        error = 2,

        /// <summary>
        /// 通知
        /// </summary>
        notice = 3

    }
}
